package com.baohua.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;

import com.baohua.dao.DictionaryDao;
import com.baohua.model.Dictionary;

@Component("dictionaryDao")
public class DictionaryDaoImpl implements DictionaryDao {

	private SessionFactory sessionFactory;
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	@Resource(name="sessionFactory")
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public long findIdByCode(String ordCtgyStr) {
		/**出错返回-1**/
		long result = -1;
		String hql = "select d.dictionaryId from Dictionary d where d.categoryCode = ?";
		Object obj = sessionFactory.getCurrentSession().createQuery(hql).setString(0, ordCtgyStr).uniqueResult();
		if(obj.equals(null))
			return result;
		result = Long.parseLong(obj.toString());
		return result;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<String> findNameForParentID(long dictionaryPId) {
		String sql = "select d.categoryName from Dictionary d where d.dictionaryPId = ?";
		
		List<String> list = sessionFactory.getCurrentSession().createQuery(sql)
				.setLong(0, dictionaryPId).list();
		return list;
	}
	
	/**
	 * 替代方法：DictionaryDao.findDictionaryByPIdAndCode
	 */
	@Deprecated
	@SuppressWarnings("unchecked")
	@Override
	public List<Dictionary> findDictionaryByCode(String categoryCode) {
		String hql = "from Dictionary d where d.dictionaryPId = " +
				"(select i.dictionaryId from Dictionary i where i.categoryCode = ?)";
		Query q = sessionFactory.getCurrentSession().createQuery(hql);
		q.setString(0, categoryCode);
		
		return (List<Dictionary>)q.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Dictionary> findDictionaryByPIdAndCode(String... categoryCodes) {
		String parameter = "";//查询的参数条件
		for(String code : categoryCodes) {
			parameter = parameter + "'" + code + "', ";
		}
		parameter = parameter.substring(0, parameter.length()-2);//截取字符串后面的：", "。
		String hql = "from Dictionary di where di.dictionaryPId in(" +
				"select d.dictionaryId from Dictionary d where d.categoryCode in(" + parameter + "))";
		return (List<Dictionary>)sessionFactory.getCurrentSession().createQuery(hql).list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Dictionary> findDictionarysByCode(String... categoryCodes) {
		String parameter = "";//查询的参数条件
		for(String code : categoryCodes) {
			parameter = parameter + "'" + code + "', ";
		}
		parameter = parameter.substring(0, parameter.length()-2);//截取字符串后面的：", "。
		List<Dictionary> dtys = (List<Dictionary>)sessionFactory.getCurrentSession().createQuery("from Dictionary d where d.categoryCode in(" + parameter + ")").list();
		return dtys;
	}
	

}
